"""
My first attempt since my Sharp Zarus days at a Qt4 application...

I am using http://zetcode.com/tutorials/pyqt4/firstprograms/ for a tutorial.

It always nice to see how much disk space you are using in a graphical kind of way.
The good old unix command du does this.
I have a Tk version of this so the translation should be a good intro.

This will only work on os x and *nix (as it used du)
"""

import sys

from subprocess import Popen, PIPE

from PyQt4.QtGui import QAction, QApplication, QFileDialog, QIcon, QMainWindow, QTextEdit

class Action(QAction):
    pass

class Icon(QIcon):
    pass

class TextEdit(QTextEdit):
    pass

class MainWindow(QMainWindow):

    def __init__(self):
        QMainWindow.__init__(self)
        self.resize(640, 480)
        self.setWindowTitle('Disk Space')

        toolbar = self.addToolBar('File')
        self.open_action = Action(Icon('images/open.png'), '&Select a folder', self, triggered=self.open_cmd)
        toolbar.addAction(self.open_action)

        self.textedit = TextEdit()
        self.textedit.setReadOnly(True)
        self.setCentralWidget(self.textedit)
        
        self.statusBar().showMessage('Ready..')

    def open_cmd(self):
        dirname = QFileDialog.getExistingDirectory(self)
        self.statusBar().showMessage('Selected %s' % (dirname or None))
        if dirname:
            # capture the output and any errors from the unix command du
            # type man du to find out about du
            output, error = Popen(['du','-d 1', dirname], stdout=PIPE,  shell=True).communicate()
            self.textedit.clear()
            if error:
                print error
            # this does not really need explaining but...
            # the output needs spliting on newline \n
            # each line is in 2 parts split on tab \t
            # the first part is the number of kb the second part is the full filename
            # convert the kb to an int to get proper sorting
            # remove the directory from the name to get the name by its self
            # sort and reverse to get the total first and the folders in size order
            # the following one liner does all this .. another reason why Python is great!
            for kb,name in reversed(sorted([(int(kb), name.replace(dirname, '')) for kb, name in [line.split('\t') for line in output.split('\n') if line]])):
                self.textedit.append('%8d Mb  %s' % (kb//1024, name or 'Total\n\n'))
        
class Application(QApplication):
    def __init__(self):
        QApplication.__init__(self, sys.argv)
        m=MainWindow()
        m.show()
        sys.exit(self.exec_())

Application()
